package com.liuke.question5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Auther: 刘科
 * @Date: 2021/07/04/19:56
 * @Description:
 */
public class Client {
    public static void main(String[] args) throws IOException {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
            Selector selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
            socketChannel.connect(new InetSocketAddress("127.0.0.1", 8088));

            while (true) {
                selector.select();
                Set<SelectionKey> keySet = selector.selectedKeys();
                keySet.forEach(selectionKey -> {
                    if (selectionKey.isConnectable()) {
                        SocketChannel client = (SocketChannel) selectionKey.channel();
                        if (client.isConnectionPending()) {
                            try {
                                client.finishConnect();
                                ByteBuffer writeByffer = ByteBuffer.allocate(1024);
                                writeByffer.put((LocalDateTime.now() + "连接成功").getBytes());
                                writeByffer.flip();
                                client.write(writeByffer);
                                ExecutorService executorService = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
                                executorService.submit(() -> {
                                    while (true) {
                                        try {
                                            writeByffer.clear();
                                            System.out.println("请输入网址：");
                                            InputStreamReader in = new InputStreamReader(System.in);
                                            BufferedReader br = new BufferedReader(in);
                                            String SendMessage = br.readLine();
                                            writeByffer.put(SendMessage.getBytes());
                                            writeByffer.flip();
                                            client.write(writeByffer);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            client.register(selector, SelectionKey.OP_READ);
                        } catch (ClosedChannelException e) {
                            e.printStackTrace();
                        }
                    } else if (selectionKey.isReadable()) {
                        SocketChannel client = (SocketChannel) selectionKey.channel();
                        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                        try {
                            int count = client.read(readBuffer);
                            if (count > 0) {
                                String receiveMessage = new String(readBuffer.array(), 0, count);
                                System.out.println("receiveMessage: " + receiveMessage);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    keySet.clear();
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
